package com.example.demo99.Task;

import com.example.demo99.Entity.Order;
import com.example.demo99.Enums.OrderStatus;
import com.example.demo99.Mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
@Component
public class OrderTimeoutTask {
    @Autowired
    private OrderMapper orderMapper;

    // 每1分钟执行一次
    @Scheduled(fixedRate = 5000)
    public void cancelTimeoutOrders() {
        // 当前时间减去30分钟
        LocalDateTime deadline = LocalDateTime.now().minusMinutes(10);

        // 查询超时未支付订单
        List<Order> timeoutOrders = orderMapper.findTimeoutOrders(deadline);

        for (Order order : timeoutOrders) {
            // 更新为已取消
            order.setStatus(OrderStatus.CANCELED);
            orderMapper.updateStatus(order.getId(), OrderStatus.CANCELED.name());
            System.out.println("订单超时自动取消，订单ID：" + order.getId());
        }
    }
}
